package cn.kone.system.interceptor;

import cn.kone.system.jwt.JwtUtil;
import cn.kone.system.jwt.Payload;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果是前台的用户那么就放行
        if("front".equals(request.getHeader("requestType"))){
            return true;
        }

        //请求中拿到token
        String token = request.getHeader("token");

        //判断token是否为空
        if (token != null) {

            try {
                //将token解析
                Payload payload = JwtUtil.parseJwtToken(token);
                //放行
                return true;
            } catch (Exception e) {
                /**
                 * 有异常就表名用户未登录
                 */
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().println("{\"success\":false,\"message\":\"快去登录吧~~~叼毛~~~\"}");
                return false;
            }

        }

        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println("{\"success\":false,\"message\":\"toLogin\"}");
        return false;
    }
}
